﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Matrix.MaKaYunShang.BLL;
using Matrix.MaKaYunShang.BLL.BllExt;
using Matrix.MaKaYunShang.Model;
using Matrix.MaKaYunShang.Model.DataStatisticsModels;
using Matrix.MaKaYunShang.Model.Dto;
using Matrix.MaKaYunShang.Model.Enum;

namespace Matrix.MaKaYunShang.MagWeb.Controllers
{
    [Matrix.MaKaYunShang.Model.Attributes.Skip]
    public class GfcStatController : BaseController
    {
        private readonly GfcStatBll _gfcStatBll = new GfcStatBll();

        #region 订单详情统计报表
        /// <summary>
        /// 订单详情统计报表
        /// </summary>
        public ActionResult OrderDetailList()
        {
            return View();
        }
        [HttpPost]
        [Matrix.MaKaYunShang.Model.Attributes.Skip]
        public ActionResult OrderDetailListing(int draw, int start, int length, DateTime? startTime = null, DateTime? endTime = null, int? shopId = null)
        {
            try
            {
                int order;
                int.TryParse(Request["order[0][column]"], out order);
                string direction = Request["order[0][dir]"];
                var orderByColumns = new[] { "id", "TotalQuantity", "SendQuantity", "CardValue", "StartTime", "EndTime", "Id" };
                string search = Request["search[value]"];

                TableDataViewDto<FullDataStatOrderDetail> theList = _gfcStatBll.QueryStatOrderDetailInfoPage(draw,
                    (start / length) + 1, length, startTime, endTime, shopId);
                JsonResult jsonResult = Json(theList);
                jsonResult.MaxJsonLength = int.MaxValue;

                return jsonResult;
            }
            catch (Exception ex)
            {
                Logger.Error("OrderDetailListing Listing Catch Error: " + ex.Message);
                return Json(false);
            }
        }

        /// <summary>
        /// 导出Excel
        /// </summary>
        public ActionResult ExportExcelStatOrderDetailInfo(DateTime? startTime = null, DateTime? endTime = null, int? shopId = null)
        {
            Result result = new Result() { Status = true };
            try
            {
                var filename = DateTime.Now.ToString("订单详情统计报表-yyyyMMddHHmmssfff") + ".xls";
                var path = System.Web.HttpContext.Current.Server.MapPath("/Files/Statistics/" + filename);
                bool resultStatus = _gfcStatBll.ExportExcelStatOrderDetailInfo(path, startTime, endTime, shopId);
                if (resultStatus)
                {
                    result.Message = "/Files/Statistics/" + filename;
                }
                else
                {
                    result.Status = false;
                    result.Message = "导出失败";
                }
            }
            catch (Exception ex)
            {
                result.Status = false;
                result.Message = ex.Message;
                Logger.Error("ExportExcelStatOrderDetailInfo  Error: " + ex.Message);
                throw;
            }
            return Json(result);
        }

        #endregion

        #region 订单统计报表

        public ActionResult OrderStatisticsList()
        {
            return View();
        }
        [HttpPost]
        [Matrix.MaKaYunShang.Model.Attributes.Skip]
        public ActionResult OrderStatisticsListing(int draw, int start, int length,
         int queryDateType = 0, bool isGroupbyShop = false, bool isGroupByPayWay = false,
            bool isGroupByOrderStatus = false, DateTime? dtBeginTime = null, DateTime? dtEndTime = null,
            int? shopId = null, int? orderPayWay = null, int? orderStatus = null)
        {
            try
            {

                TableDataViewDto<DataStatShopOrders> theList = _gfcStatBll.QueryDataStatShopOrdersPage(draw, (CommonEnum.DataStatQueryDateType)queryDateType, isGroupbyShop, isGroupByPayWay, isGroupByOrderStatus, dtBeginTime, dtEndTime, shopId, orderPayWay, orderStatus,
                    (start / length) + 1, length);
                JsonResult jsonResult = Json(theList);
                jsonResult.MaxJsonLength = int.MaxValue;

                return jsonResult;
            }
            catch (Exception ex)
            {
                Logger.Error("OrderStatisticsListing Listing Catch Error: " + ex.Message);
                return Json(false);
            }
        }

        /// <summary>
        /// 导出Excel
        /// </summary>
        public ActionResult ExportExcelDataStatShopOrdersPage(int queryDateType = 0, bool isGroupbyShop = false, bool isGroupByPayWay = false,
            bool isGroupByOrderStatus = false, DateTime? dtBeginTime = null, DateTime? dtEndTime = null,
            int? shopId = null, int? orderPayWay = null, int? orderStatus = null)
        {
            Result result = new Result() { Status = true };
            try
            {
                var filename = DateTime.Now.ToString("订单统计报表-yyyyMMddHHmmssfff") + ".xls";
                var path = System.Web.HttpContext.Current.Server.MapPath("/Files/Statistics/" + filename);
                var resutlStataus = _gfcStatBll.ExportExcelDataStatShopOrdersPage(path, (CommonEnum.DataStatQueryDateType)queryDateType, isGroupbyShop, isGroupByPayWay, isGroupByOrderStatus, dtBeginTime, dtEndTime, shopId, orderPayWay, orderStatus);
                if (resutlStataus)
                {
                    result.Message = "/Files/Statistics/" + filename;
                }
                else
                {
                    result.Message = "导出失败";
                    result.Status = false;
                }
            }
            catch (Exception ex)
            {
                result.Status = false;
                result.Message = ex.Message;
                Logger.Error("ExportExcelDataStatShopOrdersPage Error: " + ex.Message);
                throw;
            }
            return Json(result);
        }
        #endregion

        #region 销售统计

        public ActionResult SalesStatisticsList()
        {
            return View();
        }
        [HttpPost]
        [Matrix.MaKaYunShang.Model.Attributes.Skip]
        public ActionResult SalesStatisticsListing(int draw, int start, int length,
            int queryDateType = 0, bool isGroupbyShop = false,
            bool isGroupByCommodity = false, bool isGroupByPayWay = false, bool isGroupByConsumer = false,
            bool isGroupByDeliveryAccount = false, DateTime? dtBeginTime = null, DateTime? dtEndTime = null,
            int? shopId = null, int? orderPayWay = null, string commodityName = "", string commodityBarCode = "",
            int? deliveryAccountId = null, string consumerName = null)
        {
            try
            {
                TableDataViewDto<ShopDataStatShopCommoditySelling> theList =
                    _gfcStatBll.QueryStatShopCommoditySellingPage<ShopDataStatShopCommoditySelling>(draw,
                        (CommonEnum.DataStatQueryDateType)queryDateType, isGroupbyShop,
                        isGroupByCommodity, isGroupByPayWay, isGroupByConsumer,
                        isGroupByDeliveryAccount, dtBeginTime, dtEndTime,
                        shopId, orderPayWay, commodityName, commodityBarCode,
                        deliveryAccountId, consumerName, (start / length) + 1, length);
                JsonResult jsonResult = Json(theList);
                jsonResult.MaxJsonLength = int.MaxValue;

                return jsonResult;
            }
            catch (Exception ex)
            {
                Logger.Error("SalesStatistics Listing Catch Error: " + ex.Message);
                return Json(false);
            }
        }

        /// <summary>
        /// 导出Excel
        /// </summary>
        public ActionResult ExportExcelStatShopCommoditySelling(
            int queryDateType, bool isGroupbyShop = false,
            bool isGroupByCommodity = false, bool isGroupByPayWay = false, bool isGroupByConsumer = false,
            bool isGroupByDeliveryAccount = false, DateTime? dtBeginTime = null, DateTime? dtEndTime = null,
            int? shopId = null, int? orderPayWay = null, string commodityName = "", string commodityBarCode = "",
            int? deliveryAccountId = null, string consumerName = null, int pageIndex = 1, int pageSize = 50)
        {
            Result result = new Result() { Status = true };
            try
            {
                var filename = DateTime.Now.ToString("销售统计报表-yyyyMMddHHmmssfff") + ".xls";
                var path = System.Web.HttpContext.Current.Server.MapPath("/Files/Statistics/" + filename);
                var resultStataus = _gfcStatBll.ExportExcelStatShopCommoditySelling<ShopDataStatShopCommoditySelling>(path, (CommonEnum.DataStatQueryDateType)queryDateType, isGroupbyShop,
                            isGroupByCommodity, isGroupByPayWay, isGroupByConsumer,
                            isGroupByDeliveryAccount, dtBeginTime, dtEndTime,
                            shopId, orderPayWay, commodityName, commodityBarCode,
                            deliveryAccountId, consumerName);
                if (resultStataus)
                {
                    result.Message = "/Files/Statistics/" + filename;
                }
                else
                {
                    result.Status = false;
                    result.Message = "导出失败";
                }
            }
            catch (Exception ex)
            {
                result.Status = false;
                result.Message = ex.Message;
                Logger.Error("ExportExcelStatShopCommoditySelling  Error: " + ex.Message);
                throw;
            }
            return Json(result);
        }
        #endregion


        /// <summary>
        /// 搜索店铺
        /// </summary>
        [HttpPost]
        [Matrix.MaKaYunShang.Model.Attributes.Skip]
        public JsonResult GetShopList(string keyWords)
        {
            var result = new Result<List<Shops>>();
            var sysConfig = SysConfigBLL.Instance.GetModelList().FirstOrDefault();
            if (sysConfig != null)
            {
                result.Status = true;
                result.Data = ShopsBLL.Instance.GetListByName(keyWords, true);
            }
            else
            {
                result.Message = "系统配置错误！";
            }
            return Json(result);
        }

        /// <summary>
        /// 查询配送人员
        /// </summary>
        [HttpPost]
        [Matrix.MaKaYunShang.Model.Attributes.Skip]
        public JsonResult GetMcAccountsList(string keyWords, int shopId)
        {
            var result = new Result<List<McAccounts>>() { Status = true };
            result.Data = McAccountsBLL.Instance.GetModelList(string.Format(" ShopId={0} and DisplayName like'%{1}%'", shopId, keyWords));
            if (result.Data.Count == 0)
            {
                result.Status = false;
                result.Message = "未找到数据";
            }
            return Json(result);
        }
        [HttpPost]
        [Matrix.MaKaYunShang.Model.Attributes.Skip]
        public JsonResult GetCommodityLibList(string keyWords)
        {
            var result = new Result<List<CommodityLib>>();
            var commodityLibList = CommodityLibBLL.Instance.GetModelList(string.Format("CommodityName like '%{0}%'", keyWords));
            if (commodityLibList != null)
            {
                commodityLibList.ForEach(c =>
                {
                    if (c.BrandId > 0)
                    {
                        var commodityBrand = CommodityBrandBLL.Instance.GetModel(c.BrandId);
                        c.BrandName = commodityBrand != null ? commodityBrand.BrandName : string.Empty;
                    }
                });

                result = new Result<List<CommodityLib>>
                {
                    Status = true,
                    Message = "Success",
                    Data = commodityLibList
                };
            }
            else
            {
                result.Message = "商品不存在！";
            }
            return Json(result);
        }

    }
}